package com.github.tetrisgame.ui.activity;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.github.tetrisgame.databinding.ActivityMainBinding;
import com.github.tetrisgame.manager.GameCenter;
import com.github.tetrisgame.utils.Music;
import com.github.tetrisgame.utils.Person;

import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;


public class MainActivity extends AppCompatActivity {
    private  ActivityMainBinding mBinding;
    private GameCenter gameCenter = GameCenter.defaultCenter;
    private AlertDialog dialog;
    private AlertDialog dialogWin;
    private Music music = Music.defaultMusic;
    private SharedPreferences sp;



    Timer timer = new Timer();
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 设置当前窗口为全屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        music.init(this);
        music.initSp();
        initDialog();
        GameCenter.defaultCenter.bindView(mBinding.previewView,mBinding.gameView);
        GameCenter.defaultCenter.start();
        mBinding.start.setOnClickListener(v->{

            startOnClick();
        });

        Toast toast = new Toast(this);
        Person p2 = new Person();
        p2.setName("lucky");
        p2.setAddress("北京海淀");
        p2.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if(e==null){
                    toast.setText("添加数据成功，返回objectId为："+objectId);
                }else{
                    toast.setText("创建数据失败：" + e.getMessage());
                }
            }
        });



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        music.clearSp();
    }

    private void initEvent(){
        mBinding.left.setOnClickListener(v->{
            GameCenter.defaultCenter.moveLeft();

        });
        mBinding.right.setOnClickListener(v->{
            GameCenter.defaultCenter.moveRight();

        });
        mBinding.down.setOnClickListener(v->{
            GameCenter.defaultCenter.moveDown();
            music.moveMusic();
        });

        mBinding.down.setOnLongClickListener(v->{
            GameCenter.defaultCenter.moveQuickDown();
            return true;
        });
        mBinding.rotate.setOnClickListener(v->{
            GameCenter.defaultCenter.rotate();
        });
    }
    private void initDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("游戏结束")
                .setPositiveButton("再来一次", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        gameCenter.resetScore();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        gameCenter.resetScore();
                    }
                });

        dialog = builder.create();
        dialog.setCancelable(false);
        builder.setTitle("提示")
                .setMessage("闯关成功")
                .setPositiveButton("下一关", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        gameCenter.addLevel();
                        mBinding.Level.setText("Level "+gameCenter.getLevel());
                        gameCenter.resetScore();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        gameCenter.resetLevel();
                        gameCenter.resetScore();
                    }
                });
        dialogWin = builder.create();
        dialogWin.setCancelable(false);
    }
    private void startOnClick(){
        gameCenter.changeGameState();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                GameCenter.defaultCenter.moveDown();
                runOnUiThread(()->{
                    mBinding.score.setText(gameCenter.getScore()+"");
                    if (gameCenter.isWin()){
                        dialogWin.show();
                        gameCenter.clearBoards();
                        mBinding.gameView.refresh();
                        startOnClick();

                    }

                    if(gameCenter.isOver()){
                        dialog.show();
                        gameCenter.clearBoards();
                        mBinding.gameView.refresh();

                    }

                });

            }
        };
        if (!gameCenter.getGameState()){
            music.clearMp();
            timer.cancel();
            timer = new Timer();
            mBinding.left.setOnClickListener(null);
            mBinding.right.setOnClickListener(null);
            mBinding.down.setOnClickListener(null);
            mBinding.rotate.setOnClickListener(null);
        }else{
            music.initMp();
            initEvent();
            timer.schedule(timerTask,0,gameCenter.getLevel() <= 4 ?500 - (gameCenter.getLevel()-1) * 100 : 300 / (gameCenter.getLevel() - 3));
        }
    }


}